#include <stdio.h>
#include <stdlib.h>
#include <csp_spu.h>
#include <csp_debug.h>
#include "../fh_test.h"


#define CHANNEL_NAME 42


int global_pid; 


int Run(){
	int pid = csp_pid();


	global_pid = csp_pid();

	int n __attribute__ ((aligned(16)));

	printf("Worker (pid=%i) started.\n", pid);

	csp_channel farmer2workers = 
		csp_create_channel(ONE2ANY_CHANNEL, FARMER2WORKERS, sizeof(int));

	csp_channel worker2harvester = 
		csp_create_channel(ANY2ONE_CHANNEL, WORKERS2HARVESTER, sizeof(int));

	while(1){	
		//printf("Worker (pid=%i) waiting for farmer.\n", pid);
		if( csp_channel_read(farmer2workers, &n) ){
			printf("Worker (pid=%i) read from poisoned channel. Exiting..\n", pid);
			break;
		}

		//printf("w=%i\n", n);
	
		//printf("Worker (pid=%i) writing to harvester.\n", pid);
		csp_channel_write(worker2harvester, &n);
	}

	ASSERT( pid == csp_pid() );
	ASSERT( global_pid == csp_pid() );

	PRINTF_FOR_TESTING("%s terminating on spe #%i with pid %i\n",__FILE__ , csp_spe_id(), pid);

	PRINTF_FOR_TESTING("Nested task with pid=%i terminated with res=%i.\n", pid, res);

	return 0;
}
